<?php

namespace App\Http\Middleware;

use App\Http\Config\ErrorCode;
use App\Models\Saas\Mall;
use Closure;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\Facades\Response;

class ApiAuthenticate
{
    protected $app;
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $request->mallId = $request->mallId && $request->mallId != "undefined" ? $request->mallId : 1; // 后面删除
        if(empty($request->mallId)){
            return Response::json(["code" => "1", "msg" => "缺少参数mall_id"], '200', [], JSON_UNESCAPED_UNICODE);
        }
        if(!$mallData = Mall::getFields("id,admin_id,expired_time,is_delete,is_disable", ["id" => $request->mallId])){
            return Response::json(ErrorCode::code("customized", "系统不存在"), '200', [], JSON_UNESCAPED_UNICODE);
        }
        if (!empty($mallData["expiredTime"]) && $mallData["expiredTime"] <= time()) {
            return Response::json(ErrorCode::code("mall_expired"), '200', [], JSON_UNESCAPED_UNICODE);
        }
        if($mallData["isDelete"] != "0"){
            return Response::json(ErrorCode::code("customized", "系统已回收"), '200', [], JSON_UNESCAPED_UNICODE);
        }
        if($mallData["isDisable"] != "0"){
            return Response::json(ErrorCode::code("customized", "系统已禁用"), '200', [], JSON_UNESCAPED_UNICODE);
        }
        if (!empty($request->userLoginData) && $request->mallId != $request->userLoginData["mall_id"]) { // 登录了，判断当前用户是不是系统的用户
            $res = ErrorCode::code("token_expire");
            $res["msg"] = "系统mallId错误";
            return Response::json($res, '200', [], JSON_UNESCAPED_UNICODE);
        }
        $request->mallData = ["id" => $request->mallId];
        return $next($request);
    }
}
